package cc.cary.warehouse.common;

import org.springframework.lang.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * 数据库枚举常量抽象类
 *
 * @author Cary
 * @date 2023/1/16
 */
public interface DBEnum {

    @Nullable
    static <k extends Enum<k>> k of(k[] enums, String name) {
        Optional<k> one = Stream.of(enums).filter(v -> v.name().equals(name)).findFirst();
        return one.orElse(null);
    }

    @Nullable
    static <k extends Enum<k>> k of(k[] enums, Integer code) {
        Optional<k> one = Stream.of(enums).filter(v -> ((DBEnum) v).getCode().equals(code)).findFirst();
        return one.orElse(null);
    }

    @Nullable
    static <k extends Enum<k>> k ofMean(k[] enums, String mean) {
        Optional<k> one = Stream.of(enums).filter(v -> ((DBEnum) v).getMean().equals(mean)).findFirst();
        return one.orElse(null);
    }

    @Nullable
    static <k extends Enum<k>> String getMeanOf(k[] enums, String name) {
        Optional<k> one = Stream.of(enums).filter(v -> v.name().equals(name)).findFirst();
        if (one.isPresent()) {
            return ((DBEnum) one.get()).getMean();
        }
        return "";
    }

    @Nullable
    static <k extends Enum<k>> Integer getCodeOf(k[] enums, String name) {
        Optional<k> one = Stream.of(enums).filter(v -> v.name().equals(name)).findFirst();
        if (one.isPresent()) {
            return ((DBEnum) one.get()).getCode();
        }
        return 0;
    }


    static <T extends Enum<T>> Map<String, String> meanValues(Class<T> clz, T[] values) {
        Map<String, String> maps = new HashMap<>();
        Stream.of(values).forEach(v -> {
            Enum<T> e = Enum.valueOf(clz, v.name());
            DBEnum dbEnum = (DBEnum) e;
            maps.put(e.name(), dbEnum.getMean());
        });
        return maps;
    }

    static <T extends Enum<T>> Map<String, Integer> codeValues(Class<T> clz, T[] values) {
        Map<String, Integer> maps = new HashMap<>();
        Stream.of(values).forEach(v -> {
            Enum<T> e = Enum.valueOf(clz, v.name());
            DBEnum extras = (DBEnum) e;
            maps.put(e.name(), extras.getCode());
        });
        return maps;
    }


    static <T extends Enum<T>> Map<String, String> meanCodeValues(Class<T> clz, T[] values) {
        Map<String, String> maps = new HashMap<>();
        Stream.of(values).forEach(v -> {
            Enum<T> e = Enum.valueOf(clz, v.name());
            DBEnum extras = (DBEnum) e;
            maps.put(e.name(), extras.getCode() + "_" + extras.getMean());
        });
        return maps;
    }


    default String getMean() {
        return "";
    }

    default Integer getCode() {
        return 0;
    }
}
